<script>
import { getParkEnterpriceListApi, deleteParkEnterpriceApi, addEnterpriceRentContractApi } from '@/api/parkEnterprise'
import { getRentBuildingListApi } from '@/api/parkBuilding'
import { uploadFileApi } from '@/api/common'
export default {
  name: 'Building',
  data() {
    return {
      tableData: [{
        id: 15505,
        contact: '王小虎',
        contactNumber: '1316668888',
        existContractFlag: 1,
        name: '经济1111111'
      }, {
        id: 15505,
        contact: '王小虎',
        contactNumber: '1316668888',
        existContractFlag: 1,
        name: '经济1111111'
      }, {
        id: 15505,
        contact: '王小虎',
        contactNumber: '1316668888',
        existContractFlag: 1,
        name: '经济1111111'
      }],
      enterpriceListParams: {
        pageSize: '2',
        page: '1',
        name: null
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      total: 0,
      dialogFormVisible: false,
      rentBuildingList: [],
      enterpriseId: null,
      uploadEnterpriceRentContractData: {
        buildingId: null, // 租赁楼宇id
        timePickerData: [],
        startTime: '', // 开始日期
        endTime: '', // 租赁结束日期
        contractUrl: '', // 合同附件url
        contractId: null, // 合同附件id
        type: null, // number 操作类型，添加合同0，续签合同1
        enterpriseId: null // 企业id
      },
      formRole: {
        buildingId: [
          { required: true, message: '必填项', trigger: 'change' }
        ],
        timePickerData: [
          { type: 'array', required: true, message: '必填项', fields: {
            0: { type: 'string', required: true, message: '请选择开始日期' },
            1: { type: 'string', required: true, message: '请选择结束日期' }
          }}
        ],
        contractId: [
          { required: true, message: '必填项', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    getIndex() {
      return (this.enterpriceListParams.page - 1) * this.enterpriceListParams.pageSize + 1
    }
  },
  created() {
    this.getParkEnterpriceList()
    this.getRentBuildingList()
  },
  methods: {
    // 得到企业列表的方法
    async getParkEnterpriceList() {
      const res = await getParkEnterpriceListApi(this.enterpriceListParams)
      this.tableData = res.data.rows
      this.total = res.data.total
    },
    // 点击查询按钮
    searchCarCardInfo() {
      this.enterpriceListParams.page = 1
      this.getParkEnterpriceList()
    },
    // 改变分页器中的每页显示条数时，触发
    handleSizeChange(value) {
      this.enterpriceListParams.pageSize = value
      this.getParkEnterpriceList()
    },
    // 点击分页器中当前页码,触发的函数
    handleCurrentChange(value) {
      this.enterpriceListParams.page = value
      this.getParkEnterpriceList()
    },
    // 点击清空搜索框触发
    clearInput() {
      Object.assign(this.enterpriceListParams, {
        pageSize: '2',
        page: '1',
        name: null
      })
      this.getParkEnterpriceList()
    },
    // 点击编辑按钮
    editEnterprice({ row }) {
      this.$router.push({ path: `/park/enterprise/add?mode=edit&id=${row.id}` })
    },
    // 点击删除按钮
    deleteEnterprice({ row }) {
      this.$confirm('确认删除企业吗?', '温馨提示', { type: 'warning' })
        .then(async() => {
          await deleteParkEnterpriceApi(row.id)
          // 如果拿到了错误的Promise，就不用再判断code
          // if (res.code === 10000) {
          this.$message({ type: 'success', message: '删除成功' })
          // 重新获取数据
          this.getParkEnterpriceList()
          // }
        }).catch(() => {
          return
        })
    },
    // 点击开启弹框
    openDialogForm({ row }) {
      this.enterpriseId = row.id
      this.dialogFormVisible = true
    },
    // 得到可租赁楼宇列表
    async getRentBuildingList() {
      const res = await getRentBuildingListApi()
      this.rentBuildingList = res.data
    },
    // 上传文件时的钩子
    async uploadFileMethod({ file }) {
      // 组合数据，上传
      const formData = new FormData()
      formData.append('file', file)
      formData.append('type', 'contract')
      const res = await uploadFileApi(formData)
      if (res.code === 10000) {
        this.$message({ type: 'success', message: '上传成功' })
        this.uploadEnterpriceRentContractData.contractId = res.data.id
        this.uploadEnterpriceRentContractData.contractUrl = res.data.url
      }
      // 上传成功之后校验数据
      const elForm = this.$refs.elForm
      elForm.validateField('contractId')
    },
    // 上传前的钩子
    onBeforeUpload(fileData) {
      const whiteListType = ['application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/msword',
        'application/pdf']
      const fileTypeFlag = whiteListType.includes(fileData.type)
      const fileSize = fileData.size / 1024 / 1024
      if (!fileTypeFlag) {
        this.$message({ type: 'error', message: '上传文件类型错误' })
        return false
      }
      if (fileSize > 5) {
        this.$message({ type: 'error', message: '上传文件大小大于5MB' })
        return false
      }
    },
    // 移除文件时的钩子
    onRemoveFile() {
      this.uploadEnterpriceRentContractData.contractId = null
      this.uploadEnterpriceRentContractData.contractUrl = ''
      // 移除文件之后校验数据
      const elForm = this.$refs.elForm
      elForm.validateField('contractId')
    },
    // 日期选择器改变的时候
    dataPickerChange() {
      [this.uploadEnterpriceRentContractData.startTime,
        this.uploadEnterpriceRentContractData.endTime
      ] = this.uploadEnterpriceRentContractData.timePickerData
    },
    // 点击弹框的确认按钮
    confirmDialog() {
      // 组合要上传的数据
      this.uploadEnterpriceRentContractData.enterpriseId = this.enterpriseId
      // 添加合同的type0，续签为1
      this.uploadEnterpriceRentContractData.type = 0
      console.log('我确认了')
      const elForm = this.$refs.elForm
      elForm.validate(async(flag) => {
        if (flag) {
          // 移除数据里的timePickerData
          delete this.uploadEnterpriceRentContractData.timePickerData
          const res = await addEnterpriceRentContractApi(this.uploadEnterpriceRentContractData)
          if (res.code === 10000) {
            this.$message({ type: 'success', message: '添加合同成功' })
            this.dialogFormVisible = false
            this.getParkEnterpriceList()
          }
        }
      })
    },
    // 弹框打开时，清空数据
    dialogOpen() {
      this.uploadEnterpriceRentContractData = {
        ...this.uploadEnterpriceRentContractData,
        ...{
          buildingId: null, // 租赁楼宇id
          timePickerData: [],
          startTime: '', // 开始日期
          endTime: '', // 租赁结束日期
          contractUrl: '', // 合同附件url
          contractId: null, // 合同附件id
          type: null, // number 操作类型，添加合同0，续签合同1
          enterpriseId: null // 企业id
        }
      }
      console.log(this.uploadEnterpriceRentContractData)
      // // 清空所有校验
      this.$nextTick(() => {
        const elForm = this.$refs.elForm
        elForm.resetFields()
      })
    }
  }
}
</script>
<template>
  <div class="enterprise-container">
    <div class="head">
      <div class="search-area">
        <div class="search-item">
          <span class="text">
            企业名称：
          </span>
          <el-input v-model="enterpriceListParams.name" class="inputBox" placeholder="请输入企业名称" clearable @clear="clearInput" />
        </div>
        <div class="search-item">
          <el-button class="search-btn" size="mini" type="primary" @click="searchCarCardInfo">查询</el-button>
        </div>
      </div>
    </div>
    <div class="body">
      <div class="left">
        <el-button class="left-btn" size="mini" type="primary" @click="$router.push({path:'/park/enterprise/add'})">添加企业</el-button>
      </div>
    </div>
    <div class="footer">
      <!-- 表格栏 -->
      <div class="table">
        <el-table
          ref="multipleTable"
          class="table-elTable"
          :data="tableData"
          tooltip-effect="dark"
          :header-cell-style="{backgroundColor:'#f4f6f8',color:'#000000D9','font-weight':'normal'}"
          style="width: 100%;"
          :fit="true"
        >
          <el-table-column
            type="expand"
            align="center"
            min-width="10px"
          />
          <el-table-column
            label="序号"
            type="index"
            :index="getIndex"
            min-width="20px"
          />
          <el-table-column
            prop="name"
            label="企业名称"
            min-width="40px"
          />
          <el-table-column
            prop="contact"
            label="联系人"
            min-width="40px"
          />
          <el-table-column
            prop="contactNumber"
            label="联系电话"
            show-overflow-tooltip
            min-width="40px"
          />
          <el-table-column
            label="操作"
            width="300"
          >
            <template #default="scope">
              <div class="switchButton">
                <span @click="openDialogForm(scope)">添加合同</span>
                <span>查看</span>
                <span @click="editEnterprice(scope)">编辑</span>
                <span @click="deleteEnterprice(scope)">删除</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination
          :current-page="Number(enterpriceListParams.page)"
          :page-sizes="[2, 4, 5, 10]"
          :page-size="Number(enterpriceListParams.pageSize)"
          layout="total, prev, pager, next, sizes"
          :total="total"
          popper-class="carcard-pagination-select"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <el-dialog title="添加合同" width="580px" custom-class="enterpriceDialog" :visible.sync="dialogFormVisible" @open="dialogOpen">
      <template>
        <el-form ref="elForm" :model="uploadEnterpriceRentContractData" :rules="formRole">
          <el-form-item prop="buildingId" label="租赁楼宇">
            <el-select v-model="uploadEnterpriceRentContractData.buildingId" placeholder="请选择租赁的楼宇" size="medium" style="width: 380px;" :popper-append-to-body="false">
              <el-option v-for="item in rentBuildingList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item prop="timePickerData" label="租赁起止日期">
            <el-date-picker
              v-model="uploadEnterpriceRentContractData.timePickerData"
              size="medium"
              style="width: 380px;"
              type="daterange"
              range-separator="→"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions"
              @change="dataPickerChange"
            />
          </el-form-item>
          <el-form-item prop="contractId" label="租赁合同">
            <el-upload
              class="upload-demo"
              action="#"
              :limit="1"
              :http-request="uploadFileMethod"
              :before-upload="onBeforeUpload"
              :on-remove="onRemoveFile"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">支持扩展名：.doc .docx .pdf, 文件大小不得超过5M</div>
            </el-upload>
          </el-form-item>
        </el-form>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="dialogFormVisible = false">取 消</el-button>
        <el-button size="medium" type="primary" @click="confirmDialog">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.enterprise-container {
  .head {
    height: 52px;
    width: 100%;
    .search-area{
      width: 100%;
      height: 52px;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      .search-item {
        margin-right: 15px;
        .text{
          font-size: 14px;
          height: 32px;
        }
        .inputBox {
          width: 220px;
          height: 32px;
          ::v-deep .el-input__suffix {
            top: -3px;
          }
        }
        ::v-deep .el-input__inner{
            height: 32px;
        }
        .search-btn {
          width: 64px;
          height: 32px;
          font-size: 14px;
          letter-spacing:2px;
        }
      }
    }
  }
  .body {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;
    width: 100%;
    height: 40px;
    .left {
      display: flex;
      align-items: center;
      width: 184px;
      height: 40px;
      .left-btn {
        color: 14px;
        width: 88px;
        height: 32px;
      }
    }
  }
  .footer {
    width: 100%;
    min-height: 350px;
    margin-top: 30px;
    .table {
      .table-elTable {
        .switchButton {
          span {
            color: #4770ff;
            margin-right: 15px;
            cursor: pointer;
          }
        }
      }
    }
    .pagination {
      display: flex;
      justify-content: right;
      margin-top: 10px;
      align-items: center;
      width: 100%;
      height: 24px;
      ::v-deep .el-pagination button {
        min-width: 10px;
        padding: 0;
      }
    }
  }
  ::v-deep .enterpriceDialog {
    border-radius: 7px;
    .el-dialog__header {
      .el-dialog__title {
        font-size: 16px;
      }
    }
    .el-dialog__body {
      display: flex;
      justify-content: center;
      padding: 10px 20px;
      .el-form {
        width: 380px;
        .el-form-item {
          display: flex;
          margin-bottom: 10px;
          flex-direction: column;
          align-items: flex-start;
          .el-form-item__label {
            color: #000000d9;
            font-weight: 400;
          }
          .el-upload__tip {
            margin-top: 0px
          }
        }
      }
    }
    .el-dialog__footer {
      border-radius: 0 0 7px 7px;
      background-color: #f4f6f8;
      padding: 10px 0px;
      padding-right: 20px;
    }
  }
}
</style>
